<?php

namespace App\Http\Controllers;

use Auth;
use DebugBar\DebugBar;
use App\Models\User;
use App\Models\Link;
use App\Models\Topic;
use App\Models\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\TopicRequest;
use App\Handlers\ImageUploadHandler;

class TopicsController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth', ['except' => ['index', 'show']]);
        // \DebugBar::disable();
    }

	public function index(Request $request, Topic $topic, User $user, Link $link)
	{
		$topics = Topic::withOrder($request->order)->paginate(20);
        $active_users = $user->getActiveUsers();
        $links = $link->getAllCached();
        $order = $request->order;

		return view('topics.index', compact('topics','order','active_users','links'));

	}

    public function show(Request $request, Topic $topic)
    {
        if (!empty($topic->slug) && $request->slug != $topic->slug) {
            return redirect($topic->link(), 301);
        }

        return view('topics.show', compact('topic'));
    }

	public function create(Topic $topic)
	{
        $categories = Category::all();
		return view('topics.create_and_edit', compact('topic','categories'));
	}

	public function store(TopicRequest $request, Topic $topic)
	{
		$topic->fill($request->all());
        $topic->user_id = Auth::id();
        $topic->save();

		return redirect()->to($topic->link())->with('success', '成功创建话题.');
	}

	public function edit(Topic $topic)
	{
        $this->authorize('update', $topic);
        $categories = Category::all();

		return view('topics.create_and_edit', compact('topic','categories'));
	}

	public function update(TopicRequest $request, Topic $topic)
	{
		$this->authorize('update', $topic);
		$topic->update($request->all());

		return redirect()->to($topic->link())->with('success', '更新成功.');
	}

	public function destroy(Topic $topic)
	{
		$this->authorize('destroy', $topic);
		$topic->delete();

		return redirect()->route('topics.index')->with('success', '删除成功.');
	}

    public function uploadImage(Request $request, ImageUploadHandler $uploader)
    {
        //初始化返回数据, 默认失败
        $data = [
            'success' => false,
            'msg' => '上传失败',
            'file_path' => ''
        ];
        //判断是否有文件上传, 并赋值给$file
        if ($file = $request->upload_file) {
            //保存图片到本地
            $result = $uploader->save($file, 'topics', \Auth::id(), 1024);
            //图片保存成功的话
            if ($result) {
                $data['file_path'] = $result['path'];
                $data['success'] = true;
                $data['msg'] = '上传成功';
            }
        }

        return $data;
    }
}
